package com.tech.connect.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ksy.common.utils.AndroidUtil;
import com.ksy.common.utils.BaseAdapter;
import com.ksy.common.utils.BaseHolder;
import com.ksy.common.utils.ParamsUtil;
import com.ksy.common.view.GridOffsetsItemDecoration;
import com.ksy.oss.OssClient;
import com.ksy.oss.OssResult;
import com.tech.connect.R;
import com.tech.connect.api.BaseEntityOb;
import com.tech.connect.api.CurrentInfo;
import com.tech.connect.api.FuWuHttp;
import com.tech.connect.api.ImageApi;
import com.tech.connect.model.CatChoose;
import com.tech.connect.model.CatOpt;
import com.tech.connect.model.ItemCatSub;
import com.tech.connect.util.CatUtils;
import com.tech.connect.view.ImageAdder;
import com.tech.connect.zhaofuwu.ZhaoFuWuFuWuCatChooseActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PublishFuWuActivity extends BaseActivity {


    private ImageAdder imageAdder;
    private RecyclerView recycler2;
    private RecyclerView recycler3;
    private TextView tvTitle;
    private TextView tvCat;
    private TextView tvNote;
    private TextView tvMoney;
    private CatChoose mainCat;
    private CatChoose subCat;
    private List<CatOpt> allCatOpt = new ArrayList<>();
    private BaseAdapter<CatOpt, BaseHolder> adapterCat;
    private List<ItemCatSub> allUnitList = new ArrayList<>();
    private BaseAdapter unitAdapter;
    private ItemCatSub selectUnit = null;
    private Map<CatOpt, Set<CatOpt>> selectMap = new HashMap<>();
    private CheckBox checkbox;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getHeadBar().setTitle("发布服务").setRightText("完成", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> images = imageAdder.getImages();
                if (images.isEmpty()) {
                    showToast("请添加图片");
                    return;
                }
                String title = tvTitle.getText().toString().trim();
                String note = tvNote.getText().toString().trim();
                String money = tvMoney.getText().toString().trim();
                if (isEmpty(title)) {
                    showToast("请填写标题");
                    return;
                }
                if (isEmpty(note)) {
                    showToast("请填写介绍");
                    return;
                }
                if (isEmpty(money)) {
                    showToast("请填写价格");
                    return;
                }
                if (selectUnit == null) {
                    showToast("请选择价格单位");
                    return;
                }
                if (!checkbox.isChecked()) {
                    showToast("请阅读发布规则");
                    return;
                }
                List<String> integers = new ArrayList<>();
                Set<CatOpt> catOptMains = selectMap.keySet();
                Iterator<CatOpt> iterator = catOptMains.iterator();
                while (iterator.hasNext()) {
                    CatOpt next = iterator.next();
                    Set<CatOpt> catOptsSubs = selectMap.get(next);
                    if (catOptsSubs == null || catOptsSubs.isEmpty()) {
                        showToast("请选择" + next.name);
                        return;
                    }
                    Iterator<CatOpt> subItr = catOptsSubs.iterator();
                    while (subItr.hasNext()) {
                        CatOpt catOpt = subItr.next();
                        integers.add(catOpt.id);
                    }
                }
                showLog(integers);
                showLog(selectUnit);
                final Map<String, Object> map = new HashMap<>();
//                map.put("areaCode", 370100);//TODO
                map.put("content", note);
                map.put("introduce", note);
                map.put("lat", CurrentInfo.getUserInfo().lat);
                map.put("lng", CurrentInfo.getUserInfo().lng);
                map.put("price", money);
                map.put("properties", integers);
                map.put("serviceCategoryId", subCat.id);
                map.put("title", title);
                map.put("type", selectUnit.value);

                if (!images.isEmpty()) {
                    showDialog();
                    List<ParamsUtil.ParamsTwo<OssClient.FileType, String>> twoList = new ArrayList<>();
                    for (String image : images) {
                        twoList.add(ParamsUtil.getInstance().create(OssClient.FileType.Image, image));
                    }
                    OssClient.getInstance().update(activity, twoList, new OssClient.UpdatesListener() {
                        @Override
                        public void onFinish(final boolean isSuccess, List<OssResult> results, final List<String> ossUrls) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (isSuccess) {
                                        map.put("images", ImageApi.getImageParams(ossUrls));
                                        update(map);
                                    } else {
                                        showToast("图片上传失败");
                                    }
                                }
                            });

                        }
                    });
                } else {
                    update(map);
                }


            }
        });
        setContentView(R.layout.activity_publish_fuwu);
        initView();
        loadData();
    }

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditTextActivity.class);
                intent.putExtra("data", tvTitle.getText().toString().trim());
                jump2Activity(intent, 1);
            }
        });
        tvCat = findViewById(R.id.tvCat);
        tvCat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(ZhaoFuWuFuWuCatChooseActivity.class, 2);
            }
        });
        tvNote = findViewById(R.id.tvNote);
        tvNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditTextActivity.class);
                intent.putExtra("data", tvNote.getText().toString().trim());
                jump2Activity(intent, 3);
            }
        });
        tvMoney = findViewById(R.id.tvMoney);
        tvMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditNumActivity.class);
                intent.putExtra("data", tvMoney.getText().toString().trim());
                jump2Activity(intent, 4);
            }
        });
        imageAdder = findViewById(R.id.imageAdder);
        imageAdder.bindContext(this, 6);
        recycler2 = findViewById(R.id.recycler2);
        recycler2.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        recycler3 = findViewById(R.id.recycler3);
        recycler3.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
        checkbox = findViewById(R.id.checkbox);

    }

    private void loadData() {
        List<ItemCatSub> units = CatUtils.getInstance().getCatListByCode("service-unit-type");
        initUnitAdapter(units);
//        FuWuHttp.catUnitList(new BaseEntityOb<Map<String, List<ItemCatSub>>>() {
//            @Override
//            public void onDataDeal(boolean isSuccess, Map<String, List<ItemCatSub>> data, String msg) {
//                List<ItemCatSub> units = null;
//                if (data != null) {
//                    units = data.get("unit");
//                }
//                initUnitAdapter(units);
//            }
//        });
    }

    private void initUnitAdapter(List<ItemCatSub> data) {
        allUnitList.clear();
        if (data != null) {
            allUnitList.addAll(data);
        }
        if (unitAdapter == null) {
            unitAdapter = new BaseAdapter<ItemCatSub, BaseHolder>(R.layout.item_layout_cat_uint, allUnitList) {
                @Override
                protected void convert(BaseHolder helper, int position) {
                    ItemCatSub catOpt = allUnitList.get(position);
                    ImageView iv = helper.getView(R.id.iv);
                    if (catOpt.equals(selectUnit)) {
                        iv.setImageResource(R.drawable.icon_checkbox_checked);
                    } else {
                        iv.setImageResource(R.drawable.icon_checkbox);
                    }
                    TextView tv = helper.getView(R.id.tv);
                    tv.setText(catOpt.description);
                }
            };
            unitAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    selectUnit = allUnitList.get(position);
                    unitAdapter.notifyDataSetChanged();
                }
            });
            recycler3.setAdapter(unitAdapter);
        }
        unitAdapter.notifyDataSetChanged();
    }


    private void loadCatOpt(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        FuWuHttp.catOptList(map, new BaseEntityOb<List<CatOpt>>() {
            @Override
            public void onDataDeal(boolean isSuccess, List<CatOpt> data, String msg) {
                initCatAdapter(data);
            }
        });
    }

    private void initCatAdapter(List<CatOpt> catOpts) {
        allCatOpt.clear();
        if (catOpts != null) {
            allCatOpt.addAll(catOpts);
        }
        for (CatOpt catOpt : allCatOpt) {
            selectMap.put(catOpt, new HashSet<CatOpt>());
        }
        if (adapterCat == null) {
            adapterCat = new BaseAdapter<CatOpt, BaseHolder>(R.layout.item_layout_cat_opt, allCatOpt) {
                @Override
                protected void convert(BaseHolder helper, int position) {
                    final CatOpt catOpt = allCatOpt.get(position);
                    TextView tvTag = helper.getView(R.id.tvTag);
                    RecyclerView recycler = helper.getView(R.id.recycler);
                    tvTag.setText(catOpt.name);
                    GridOffsetsItemDecoration offsetsItemDecoration = new GridOffsetsItemDecoration(
                            GridOffsetsItemDecoration.GRID_OFFSETS_VERTICAL);
                    offsetsItemDecoration.setVerticalItemOffsets(AndroidUtil.dip2px(8));
                    offsetsItemDecoration.setHorizontalItemOffsets(AndroidUtil.dip2px(8));
                    recycler.addItemDecoration(offsetsItemDecoration);
                    recycler.setLayoutManager(new GridLayoutManager(activity, 3));
                    List<CatOpt> childs = catOpt.childs;
                    final List<CatOpt> catOptList = new ArrayList<>();
                    if (childs != null) {
                        catOptList.addAll(childs);
                    }
                    final BaseAdapter adapter = new BaseAdapter<CatOpt, BaseHolder>(R.layout.item_layout_text, catOptList) {
                        @Override
                        protected void convert(BaseHolder helper, int position) {
                            CatOpt catOptSub = catOptList.get(position);
                            TextView view = helper.getView(R.id.tv);
                            view.setText(catOptSub.name);
                            if (selectMap.containsKey(catOpt)) {
                                Set<CatOpt> catOptsSubs = selectMap.get(catOpt);
                                if (catOptsSubs != null && catOptsSubs.contains(catOptSub)) {
                                    view.setSelected(true);
                                    view.setBackgroundResource(R.drawable.common_shape_corner5_stroke_yellow);
                                } else {
                                    view.setSelected(false);
                                    view.setBackgroundResource(R.drawable.common_shape_corner5_stroke_gray);
                                }
                            } else {
                                view.setSelected(false);
                                view.setBackgroundResource(R.drawable.common_shape_corner5_stroke_gray);
                            }
                        }
                    };
                    adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            CatOpt catOptSub = catOptList.get(position);
                            if (selectMap.containsKey(catOpt)) {
                                Set<CatOpt> catOptsSubs = selectMap.get(catOpt);
                                if (catOptsSubs != null) {
                                    if (catOptsSubs.contains(catOptSub)) {
                                        catOptsSubs.remove(catOptSub);
                                    } else {
                                        catOptsSubs.add(catOptSub);
                                    }
                                } else {
                                    HashSet<CatOpt> catOptsNew = new HashSet<>();
                                    catOptsNew.add(catOptSub);
                                    selectMap.put(catOpt, catOptsNew);
                                }
                            } else {
                                HashSet<CatOpt> catOptsNew = new HashSet<>();
                                catOptsNew.add(catOptSub);
                                selectMap.put(catOpt, catOptsNew);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    });
                    recycler.setAdapter(adapter);
                }
            };
            adapterCat.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {

                }
            });
            recycler2.setAdapter(adapterCat);
        }
        adapterCat.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK) {
            imageAdder.onImagePickResult(requestCode, resultCode, intent);
            if (requestCode == 1) {
                String data = intent.getStringExtra("data");
                tvTitle.setText(data);
            } else if (requestCode == 2) {
                selectMap.clear();
                initCatAdapter(null);
                Serializable mainCatS = intent.getSerializableExtra("mainCat");
                Serializable subCatS = intent.getSerializableExtra("subCat");
                if (mainCatS != null && subCatS != null && mainCatS instanceof CatChoose && subCatS instanceof CatChoose) {
                    mainCat = (CatChoose) mainCatS;
                    subCat = (CatChoose) subCatS;
                    tvCat.setText(mainCat.name + "/" + subCat.name);
                    loadCatOpt(subCat.id);
                } else {
                    mainCat = null;
                    subCat = null;
                    tvCat.setText("");
                }
            } else if (requestCode == 3) {
                String data = intent.getStringExtra("data");
                tvNote.setText(data);
            } else if (requestCode == 4) {
                String data = intent.getStringExtra("data");
                tvMoney.setText(data);
            }
        }
    }

    private void update(Map<String, Object> map) {

        String s = new Gson().toJson(map);
        showLog(s);
        FuWuHttp.create(map, new BaseEntityOb<String>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onDataDeal(boolean isSuccess, String data, String msg) {
                showToast(msg);
                hideDialog();
                if (isSuccess) {
                    setResult(RESULT_OK);
                    destroyActivity();
                }
            }
        });
    }
}